﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySql.Data.MySqlClient;
using System.Collections.Generic;

namespace _0812159_0812164.dao
{
    public class UserDAO
    {
        public static User kiemtradangnhap(string username, string password)
        {
            User user = new User();
            DataHelper helper = new DataHelper();

            String sql = String.Format("SELECT * FROM USER WHERE username=_utf8'{0}' AND password = _utf8'{1}'", username, password);
            helper.open();
            MySqlDataReader reader = helper.executeQuery(sql);
            while (reader.Read())
            {
                user.Username = reader.GetString("username");
                user.Password = reader.GetString("password");
                break;
            }

            helper.close();

            return user;
        }
        public static int kiemtratontai(string username)
        {
            User user = new User();
            DataHelper helper = new DataHelper();
            helper.open();
            String sql = String.Format("SELECT * FROM USER WHERE username=_utf8'{0}'", username);
            helper.open();
            MySqlDataReader reader = helper.executeQuery(sql);
            while (reader.Read())
            {
                user.Username = reader.GetString("username");
                user.Password = reader.GetString("password");
                break;
            }

            helper.close();

            if (user.Username != null && user.Username!="")
                return 1;
            return -1;
        }
        public static bool dangky(string username, string password)
        {
            bool rs = false;
            if (kiemtratontai(username) == 1)
                return rs;

            DataHelper helper = new DataHelper();
            String sql = String.Format("INSERT INTO USER VALUES(_utf8'{0}',_utf8'{1}')", username, password);
            helper.open();
            rs = helper.executeUpdate(sql);
            helper.close();

            return rs;
        }

        public static List<User> getListUser()
        {
            List<User> list = new List<User>();
            DataHelper helper = new DataHelper();
            helper.open();
            string sql = "SELECT username FROM USER";
            helper.open();
            MySqlDataReader reader = helper.executeQuery(sql);
            while (reader.Read())
            {
                User user = new User();
                user.Username = reader.GetString("username");
                list.Add(user);
            }
            helper.close();

            return list;
        }
    }
}
